﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Text;
using System.Threading.Tasks;

namespace WcfInspectorLib
{
    [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Method, 
        AllowMultiple = true)]
    public class AuthorizeAttribute : Attribute //, IOperationBehavior, IOperationInvoker
    {
        //private MethodInfo _methodInfo;

        //private IOperationInvoker _oldInvoker;

        public string NameSpace { get; set; }

        public bool IsNeeded { get; set; }

        //public bool IsSynchronous => _oldInvoker.IsSynchronous;

        public AuthorizeAttribute(string ns, bool isNeeded = true)
        {
            NameSpace = ns;
            IsNeeded = isNeeded;
        }

        //public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
        //{
            
        //}

        //public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
        //{
            
        //}

        //public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
        //{
        //    _methodInfo = operationDescription.SyncMethod;
        //    _oldInvoker = dispatchOperation.Invoker;
        //    dispatchOperation.Invoker = this;
        //}

        //public void Validate(OperationDescription operationDescription)
        //{
            
        //}

        //public object[] AllocateInputs()
        //{
        //    return _oldInvoker.AllocateInputs();
        //}

        //public object Invoke(object instance, object[] inputs, out object[] outputs)
        //{
        //    if (IsNeeded)
        //    {
        //        int index = OperationContext.Current.IncomingMessageHeaders.FindHeader("AccessToken", NameSpace);
        //        if (index < 0) throw new FaultException("缺失AccessToken验证信息！");
        //        var accessToken = OperationContext.Current.IncomingMessageHeaders.GetHeader<string>(index).ToString();
        //        //从缓存中查找对应accessToken的用户信息，写入当前OperationContext的Principal
        //    }

        //    object result = _oldInvoker.Invoke(instance, inputs, out outputs);
        //    return result;

        //}

        //public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
        //{
        //    return _oldInvoker.InvokeBegin(instance, inputs, callback, state);
        //}

        //public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
        //{
        //    return _oldInvoker.InvokeEnd(instance, out outputs, result);
        //}
    }
}
